<template>
  <page-header-wrapper :title="false">
    <a-card
      :loading="loading"
      title="文章详情"
    >
      <a-form-model
        ref="articleForm"
        layout="vertical"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        :rules="articleRules"
        :model="articleForm"
      >
        <a-form-model-item label="一级分类" prop="category_id">
          <a-select v-model="articleForm.category_id" placeholder="选择文章分类" @change="onChangeCategory">
            <a-select-option v-for="item in categoryOpts" :key="item.id" :value="item.id">{{item.title}}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="文章标题" prop="title">
          <a-input type="text" placeholder="输入文章标题" v-model="articleForm.title"/>
        </a-form-model-item>
        <a-form-model-item label="文章标识（英文标识，只允许含有:英文、数字和中划线）" prop="title">
          <a-input type="text" placeholder="输入文章标识" v-model="articleForm.name"/>
        </a-form-model-item>
        <a-form-model-item label="关联关键字（牵扯顾问端详情页推荐内容，谨慎填写）" prop="keyword">
          <a-input type="text" placeholder="输入相同类型文章的关键字，例如：商标注册费用" v-model="articleForm.keyword"/>
        </a-form-model-item>
        <a-form-model-item label="封面图" prop="cover">
<!--          <a-upload-->
<!--            name="file"-->
<!--            :action="uploadUrl"-->
<!--            :headers="headers"-->
<!--            @change="onChangeUpload"-->
<!--            v-model="articleForm.cover"-->
<!--          >-->
<!--            <a-button> <a-icon type="upload" /> 上传封面图 </a-button>-->
<!--          </a-upload>-->
          <a-upload
            name="file"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            :action="uploadUrl"
            :headers="headers"
            :before-upload="beforeUpload"
            @change="onChangeUpload"
          >
            <img v-if="articleForm.cover" :src="articleForm.cover" style="width: 100px" alt="avatar" />
            <div v-else>
              <a-icon :type="uploadLoading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">
                上传封面图
              </div>
            </div>
          </a-upload>
        </a-form-model-item>
        <a-form-model-item label="文章描述" prop="description">
          <a-input type="textarea" v-model="articleForm.description"/>
        </a-form-model-item>
        <a-form-model-item label="文章内容" prop="content">
          <quill-editor :value="articleForm.content" @change="onChange"></quill-editor>
        </a-form-model-item>
        <a-form-model-item label="外链（外链地址必须带http或https）" prop="link">
          <a-input type="text" placeholder="输入文章外链" v-model="articleForm.link" />
        </a-form-model-item>
        <a-form-model-item label="排序值（排序值越小越前）" prop="sort">
          <a-input type="text" placeholder="设置排序" v-model="articleForm.sort" />
        </a-form-model-item>
        <a-form-model-item label="上传附件" prop="filename">
          <a-upload
            name="file"
            accept=".pdf"
            :headers="headers"
            :action="uploadUrl"
            @change="onUpload"
          >
            <a-button type="primary" size="small" icon="upload">上传附件(.pdf)</a-button>
          </a-upload>
        </a-form-model-item>
        <a-form-model-item label="状态" prop="status">
          <a-radio-group v-model="articleForm.status">
            <a-radio :key="index" :value="index" v-for="(item, index) in statusOpts">{{item}}</a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="选择要发布的公司" prop="company">
          <a-checkbox-group v-model="articleForm.company">
            <a-checkbox v-for="(item,index) in companyOpts" :key="index" :value="index">
              {{item}}
            </a-checkbox>
          </a-checkbox-group>
        </a-form-model-item>
        <a-divider />
        <a-form-model-item style="text-align: right">
          <a-button type="primary" style="margin-right:5px" @click="confirmSend" v-if="!isEdit">确认添加</a-button>
          <a-button type="primary" style="margin-right:5px" @click="confirmSend1" v-else>保存修改</a-button>
          <a-button type="default" @click="reset">重置表单</a-button>
        </a-form-model-item>
      </a-form-model>
    </a-card>
  </page-header-wrapper>
</template>

<script>
  import QuillEditor from '@/components/Editor/QuillEditor'
  import {
    getArticleListAdd,
    getArticleListEdit,
    postArticleListAdd,
    postArticleListEdit
  } from '@/api/article'
  import storage from 'store'
  import { ACCESS_TOKEN } from '@/store/mutation-types'
  import apis from '@/api'

  export default {
    props: {
      isEdit: {
        type: Boolean,
        default: false
      }
    },
    components: {
      QuillEditor
    },
    name: 'ArticleDetail',
    data () {
      return {
        labelCol: { span: 0 },
        wrapperCol: { span: 12 },
        articleForm: {},
        articleRules: {
          category_id: [{ required: true, message: '必须选择文章分类', trigger: 'blur' }],
          title: [{ required: true, message: '必须填写文章标题', trigger: 'blur' }],
          keyword: [{ required: true, message: '必须填写关联关键字', trigger: 'blur' }],
          content: [{ required: true, message: '必须填写文章内容', trigger: 'blur' }],
          company: [{ required: true, message: '必须选择要发布的公司', trigger: 'blur' }]
        },
        categoryOpts: {},
        statusOpts: {},
        headers: { 'Access-Token': storage.get(ACCESS_TOKEN) },
        uploadUrl: apis.Upload,
        loading: true,
        company: [],
        id: '',
        cid: '',
        companyOpts: {},
        uploadLoading: false
      }
    },
    activated () {
      this.id = this.$route.params.id
      this.loading = true
      if (this.isEdit) {
        this.getEdit(this.$route.params.id)
      } else {
        this.getAdd()
      }
    },
    methods: {
      getEdit (id) {
        getArticleListEdit(id).then(res => {
          this.categoryOpts = res.result.categoryOpts
          this.companyOpts = res.result.companyOpts
          this.statusOpts = res.result.statusOpts
          this.articleForm = res.result.article
          this.articleForm['company'] = res.result.company
          this.articleForm['status'] = res.result.status
          // this.articleForm['category_id'] = res.result.category
        }).finally(() => {
          this.loading = false
        })
      },
      getAdd () {
        getArticleListAdd().then(res => {
          this.categoryOpts = res.result.categoryOpts
          this.statusOpts = res.result.statusOpts
          this.companyOpts = res.result.companyOpts
        }).finally(() => {
          this.loading = false
        })
      },
      onChange (html) {
        this.articleForm.content = html
      },
      confirmSend () {
        const app = this
        const data = {}
        app.$refs.articleForm.validate(valid => {
          if (valid) {
            app.$confirm({
              title: '确认添加文章吗',
              onOk: () => {
                for (const k in app.articleForm) {
                  if (k !== 'company') {
                    data['article[' + k + ']'] = app.articleForm[k]
                  }
                }
                data['company'] = app.articleForm.company
                postArticleListAdd(data).then(res => {
                  if (res.status === 0) {
                    app.$message.success('添加成功')
                    app.articleForm = {}
                    app.cid = ''
                    app.$router.push({ name: 'ArticleList' })
                  } else {
                    app.$warning({
                      title: res.msg
                    })
                  }
                })
              }
            })
          } else {
            return false
          }
        })
      },
      confirmSend1 () {
        const app = this
        const data = {}
        app.$refs.articleForm.validate(valid => {
          if (valid) {
            app.$confirm({
              title: '确认修改文章吗',
              onOk: () => {
                for (const k in app.articleForm) {
                  if (k !== 'company') {
                    data['article[' + k + ']'] = app.articleForm[k]
                  }
                }
                data['company'] = app.articleForm['company']
                postArticleListEdit(app.id, data).then(res => {
                  if (res.status === 0) {
                    app.$message.success('修改成功')
                    app.$router.push({ name: 'ArticleList' })
                  } else {
                    app.$warning({
                      title: res.msg
                    })
                  }
                })
              }
            })
          } else {
            return false
          }
        })
      },
      onChangeUpload (info) {
        if (info.file.status === 'uploading') {
          this.uploadLoading = true
        }
        if (info.file.status === 'done') {
          this.articleForm.cover = info.file.response.result.url
          this.uploadLoading = false
        }
      },
      beforeUpload (file) {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
        if (!isJpgOrPng) {
          this.$message.error('请上传图片格式')
        }
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isLt2M) {
          this.$message.error('Image must smaller than 2MB!')
        }
        return isJpgOrPng && isLt2M
      },
      reset () {
        this.articleForm = {}
      },
      onChangeCategory (key) {
        this.articleForm.category_id = key
      },
      onUpload (info) {
        if (info.file.status === 'uploading') {
          return false
        }
        if (info.file.status === 'done') {
          this.articleForm.filename = info.file.name
          this.articleForm.file = info.file.response.result.url
        }
      }
    }
  }
</script>

<style scoped>

</style>
